<template>
  <div class="app-container">
    <div class="top-container" style="display: flex;margin: 0 0 20px 0;width: 100%;">
      <div style="width: 100%;display: flex;justify-content: space-between;">
        <div style="width: 70%;">
          <el-input placeholder="请输入内容" v-model="input3" class="input-with-select" style="width: 80%;">
            <el-select v-model="select" slot="prepend" placeholder="请选择查询类型" style="width: 170px;">
              <el-option label="依据记录编号" value="1"></el-option>
              <el-option label="依据船只编号" value="2"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="SearchRecords"></el-button>
          </el-input>
        </div>
        <div style="">
          <el-button type="success" @click="handleExport">导出Excel</el-button>
        </div>
      </div>
    </div>
    <div style="display: flex;width: 100vw;">
      <div style="width: 66%;">
        <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
          <el-table-column align="center" label="记录编号" width="105px" sortable>
            <template slot-scope="scope">
              {{ scope.$index + 1}}
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="船只编号" width="160" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.shipId }}</span>
            </template>
          </el-table-column>
          <el-table-column label="捕捞方式" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ getTypeLabel(scope.row.way) }}</span>
            </template>
          </el-table-column>
        <el-table-column class-name="status-col" label="捕捞地点" width="160" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.locationX + ',' + scope.row.locationY | statusFilter">{{ formatLatitude(scope.row.locationX) + ',' + formatLongitude(scope.row.locationY) }}</el-tag>
          </template>
        </el-table-column>
          <el-table-column align="center" prop="created_at" label="出海时间" width="200" sortable>
            <template slot-scope="scope">
              <i class="el-icon-time" />
              <span>{{ scope.row.beginTime }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="created_at" label="返回时间" width="200" sortable>
            <template slot-scope="scope">
              <i class="el-icon-time" />
              <span>{{ scope.row.endTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="成果汇报" width="80">
            <template slot-scope="scope">
            <el-button type="text" @click="handleProduct(scope.row.id)">详情</el-button>
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="审核状态" width="100" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status | statusFilter">{{ handleStatus(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="width: 20%;">
        <el-card style="border-radius: 16px;width: 90%;margin-left: 20px;">
          <div slot="header" class="clearfix">
            <span style="font-weight: bold;font-size: 20px;">上报捕捞记录须知</span>
            <p style="color: grey;">上报海洋捕捞记录是海洋捕捞的重要环节，请各位渔民严格遵循以下要求和上报格式规定，积极配合工作</p>
          </div>
          <div>
            <p>1. 船只编号填写此次出海捕捞所使用的船只</p>
            <p>2. 捕捞地点请严格按经度，纬度格式输入</p>
            <p>3. 【-40，-60为南纬40，西经60，正的话为北纬和东经】</p>
            <p>4. 成果汇报请如实填写，以便系统进行分析</p>
            <el-button type="danger" icon="el-icon-upload2" @click="dialogFormVisible = true">上报捕捞记录</el-button>
          </div>
        </el-card>
      </div>
    </div>
    <div style="margin-top: 40px;">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage4"
        background :page-sizes="[10, 50, 100, 200]" :page-size="10" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog title="捕捞成果明细(以斤为单位)" :visible.sync="dataForm">
      <el-form :model="form">
        <el-form-item label="鱼类" :label-width="formLabelWidth">
          <el-input v-model="form.fish" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="虾蟹类" :label-width="formLabelWidth">
          <el-input v-model="form.sac" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="壳类" :label-width="formLabelWidth">
          <el-input v-model="form.shell" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="藻类" :label-width="formLabelWidth">
          <el-input v-model="form.alga" autocomplete="off" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dataForm = false">取 消</el-button>
        <el-button type="primary" @click="dataForm = false">确 定</el-button>
      </div>
    </el-dialog>
    <!--点击上報打开的对话框，不要放在table里，单独拿出来就行，不然有多少条记录就会渲染出多少个，非常卡-->
    <el-dialog title="上报捕捞记录" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="船只编号" :label-width="formLabelWidth">
          <el-input v-model="form.shipId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="捕捞方式" :label-width="formLabelWidth">
          <el-select v-model="form.way" placeholder="请选择">
            <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="捕捞地点-经度" :label-width="formLabelWidth">
          <el-input v-model="form.locationY" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="捕捞地点-维度" :label-width="formLabelWidth">
          <el-input v-model="form.locationX" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出海时间" :label-width="formLabelWidth">
          <el-date-picker v-model="form.beginTime" type="datetime" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="返回时间" :label-width="formLabelWidth">
          <el-date-picker v-model="form.endTime" type="datetime" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="鱼类(斤为单位)" :label-width="formLabelWidth">
          <el-input v-model="form.fish" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="虾蟹类(斤为单位)" :label-width="formLabelWidth">
          <el-input v-model="form.sac" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="壳类(斤为单位)" :label-width="formLabelWidth">
          <el-input v-model="form.shell" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="藻类(斤为单位)" :label-width="formLabelWidth">
          <el-input v-model="form.alga" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="success" @click="UpdateRecord ">上报</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { F_exportRecord } from '@/api/excel'
import { getRecordList,searchRecord,updateRecord,getProduct } from '@/api/table'
//import {Edit, Delete,Search} from '@element-plus/icons-vue'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      input3: '',
      select: '',
      pageNum: 0, // 当前页码，通常初始化为1
      pageSize: 10, // 每页显示的记录数
      dialogVisible: false,
      dialogFormVisible: false,
      dataForm:false,
      form: {
        shipId: '',
        locationX: '',
        locationY:'',
        beginTime: '',
        endTime: '',
        delivery: false,
        type: [],
        fish: '0',
        sac: '0',
        shell: '0',
        alga: '0',

      },
      formLabelWidth: '120px',
      options1: [{
        value: '1',
        label: '123456'
      }, {
        value: '5',
        label: '588888'
      }, {
        value: '7',
        label: '777777'
      }, {
        value: '3',
        label: '369852'
      }],
      value1: '',
      options2: [{
        value: '0',
        label: '拖网'
      }, {
        value: '1',
        label: '围网'
      }, {
        value: '2',
        label: '流刺网'
      }, {
        value: '3',
        label: '渔笼'
      }, {
        value: '4',
        label: '其他'
      }],
      value2: ''
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleSizeChange(newSize) {
      // 当每页显示的记录数变化时触发
      this.pageSize = newSize;
      this.fetchData();
    },
    handleCurrentChange(newPageNum) {
      // 当页码变化时触发
      this.pageNum = newPageNum;
      this.fetchData();
    },
    handleProduct(id){
      this.dataForm = true
      let currentId=id
      getProduct(currentId).then(response=>{
        let productNum = response.data
        console.log(productNum)
        this.form.alga=productNum.alga_total
        this.form.fish=productNum.fish_total
        this.form.sac=productNum.sac_total
        this.form.shell=productNum.shell_total
      })
    },
    // 格式化纬度
    formatLatitude(value) {
      if (!value) return '';
      const numericValue = parseFloat(value);
      return numericValue < 0
        ? `${Math.abs(numericValue)}°S`
        : `${numericValue}°N`;
    },
    // 格式化经度
    formatLongitude(value) {
      if (!value) return '';
      const numericValue = parseFloat(value);
      return numericValue < 0
        ? `${Math.abs(numericValue)}°W`
        : `${numericValue}°E`;
    },
    handleStatus(status){
      const sta = {
      '1': '已通过',
      '0': '未通过',
    };
    return sta[status] ;
    },
    handleExport(){
      let s = this.select
      let k = this.input3
      if (this.select === ''|| this.select === null || this.select === undefined) {
          s = -1
      }
      if (this.input3 === ''|| this.input3 === null || this.input3 === undefined) {
          k = "null"
      }
      return F_exportRecord({
        keyword:k,
        searchType:parseInt(s),
        status:parseInt(-1)}) // 渔民status恒为-1
    },

    fetchData() {
      this.listLoading = true
      getRecordList(this.pageNum,this.pageSize).then(response => {
          if (response.code === 200) {
            const entries= Object.entries(response.data)
            console.log(entries)

        // 拿到total和num
            const [total,num]=entries[0]
            console.log("total=",total)
            console.log("value=",num)
            this.total=num
        
        //拿到list和数据
            const [key,value]=entries[1]
            console.log("key=",key)
            console.log("value=",value)

            this.list = value
            console.log("list=",this.list)
            this.listLoading = false
          } else {
            // 处理错误情况
            console.error(response.msg);
          }
        })
        .catch(error => {
          console.error(error);
        });
    },
    
    SearchRecords() {
      this.listLoading = true;
      searchRecord({keyword:this.input3,
        pageNum:parseInt(this.pageNum),
        pageSize:parseInt(this.pageSize),
        searchType:parseInt(this.select)}).then(response=>{
        // 使用Object.entries()获取键值对数组
        const entries= Object.entries(response.data)
        console.log(entries)

        // 拿到total和num
        const [total,num]=entries[0]
        console.log("total=",total)
        console.log("value=",num)
        this.total=num
        
        //拿到list和数据
        const [key,value]=entries[1]
        console.log("key=",key)
        console.log("value=",value)

        this.list = value
        console.log("list=",this.list)
        this.listLoading = false
      });
    },
    formatDate(date) {
    return date.toISOString().replace('T', ' ').replace(/\..*$/, '');
    },
    //更改日期格式
    formatDate(date) {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = (`0${d.getMonth() + 1}`).slice(-2); // 加1以匹配从一月开始的月份
    const day = (`0${d.getDate()}`).slice(-2);
    const hour = (`0${d.getHours()}`).slice(-2);
    const minutes = (`0${d.getMinutes()}`).slice(-2);
    const seconds = (`0${d.getSeconds()}`).slice(-2);
    return `${year}-${month}-${day} ${hour}:${minutes}:${seconds}`;
  },
  UpdateRecord() {
    // 确保form中的时间是Date对象或者能够被new Date()解析的字符串
    const formattedBeginTime = this.formatDate(this.form.beginTime);
    const formattedEndTime = this.formatDate(this.form.endTime);
    
    const payload = {
      shipId:this.form.shipId,
      locationX:this.form.locationX,
      locationY:this.form.locationY,
      beginTime: formattedBeginTime,
      endTime: formattedEndTime,
      way:this.form.way,
      // 这里添加其他表单项
      fish: this.form.fish,
      sac: this.form.sac,
      shell: this.form.shell,
      alga: this.form.alga
      // 确保所有的表单项都已正确格式化
    };

    // 使用格式化后的payload来发送数据
    updateRecord(payload).then(response => {

        if (response.code === 200) {
          this.$message.success(response.msg);
        }
        else{
          this.$message.error(response.msg);
        }
      })
  },
  getTypeLabel(typeValue) {
    const typeLabels = {
      '0': '拖网',
      '1': '围网',
      '2': '流刺网',
      '3':'鱼龙',
      '4':'其它'
      // 如果有更多类型，请继续添加
    };
    return typeLabels[typeValue] || '未知类型';
  },
    test() {
      console.log(search_type)
      search_type = 'aaa'
      console.log(search_type)
    }
  }
}
</script>

<style>
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.app-container {
  /* width: 100vw; */
}
</style>
